import { constantRoutes, otherRouter } from '@/router'
import user from './user'
import Layout from '@/layout'

/**
 * 获取一个路由组件
 * @param {*} node  节点信息
 */
function getRouter(node, component, isRoot = false) {
  const temp = {
    path: isRoot ? node.url : node.url.replace('/', ''),
    component: component,
    name: node.name,
    meta: { title: node.name, icon: node.icon },
    hidden: (node.hidden === 1)
  }
  if (isRoot && node.children) {
    temp.children = []
  }

  // isRoot && (temp.children = [])
  isRoot && (temp.alwaysShow = true)
  return temp
}

/**
 * 组件component
 * @param {*} url  节点url转换
 */
function findComponentByPath(url) {
  return (resolve) => require([`@/views${url}`], resolve)
}

export function filterAsyncRoutes(menus, isRoot = true) {
  const routers = []
  let component
  menus.forEach(menu => {
    let route = Object.assign({})
    try {
      if (isRoot) {
        route = getRouter(menu, Layout, true)
      } else if (menu.children && menu.children.length > 0) {
        const result = menu.children.find((item) => {
          component = findComponentByPath(item.path)
          return component
        })
        if (result) {
          route = getRouter(result, component, true)
        } else {
          return
        }
      } else {
        if (!menu.path) { return }
        component = findComponentByPath(menu.path)
        if (!component) { return }
        route = getRouter(menu, component)
      }
      if (menu.children && menu.children.length > 0 && isRoot) {
        route.children = route.children.concat(filterAsyncRoutes(menu.children, false))
      }
    } catch (error) { console.log(error); return }

    routers.push(route)
  })
  return routers
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

function filterNotFoundRouter(menus) {
  const routers = filterAsyncRoutes(menus)

  let newRouters = []
  routers.forEach(route => {
    try {
      if (route.children.length > 0) {
        route.redirect = route.children[0].path
        newRouters = newRouters.concat(route)
      }
    } catch (err) { console.log(err) }

    return route
  })

  return newRouters
}

function getOwnRoutes(menus) {
  let routers = filterNotFoundRouter(menus)
  routers = routers.concat(otherRouter)
  return routers
}

// 设置系统菜单和路由
const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      const { menu } = user.state
      const accessedRoutes = getOwnRoutes(menu)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
